//
//  BDImagePickerManager.m
//  ProjectForBD
//
//  Created by Jaesun on 16/12/16.
//  Copyright © 2016年 B.D. All rights reserved.
//

#import "BDImagePickerManager.h"
#import <ImageIO/ImageIO.h>

#import "UIImage+SJCategory.h"

static BDImagePickerManager *imagePickerManager = nil;

@implementation BDImagePickerManager

+ (instancetype)shareImagePickerManager {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        imagePickerManager = [[BDImagePickerManager alloc] init];
    });
    return imagePickerManager;
}

/**
 初始化相机、相册并回调 结果图片

 @param type 相机/相册
 @param preController 掉用相机/相册的控制器
 @param completion 返回的图片
 */
- (void)imagePickerWithSourceType:(UIImagePickerControllerSourceType)type inViewController:(UIViewController *)preController completion:(Completion)completion {
    
    self.preController  = preController;
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    imagePicker.delegate = self;
    
    if ([self isCameraAvailable:type]) {
        [imagePicker setSourceType:type]; // 设置类型
        [preController presentViewController:imagePicker animated:YES completion:^{
            NSLog(@"presentVC");
        }];
    }
    else {
        NSLog(@"无权限");
    }
    self.completion = completion;
}


/**
 是否有访问相机或相册的权限

 @return YES 有；NO 无
 */
- (BOOL)isCameraAvailable:(UIImagePickerControllerSourceType)type{
    return [UIImagePickerController isSourceTypeAvailable:type];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *theImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSDictionary * imageMetadata = info[@"UIImagePickerControllerMediaMetadata"];
    // 原始图片
    UIImage *resultImage = theImage;
//    NSData *imgData = UIImageJPEGRepresentation(resultImage, 1.0);
   
    CGRect rect = [[UIScreen mainScreen] bounds];
    CGSize size = rect.size;
    
    CGFloat width = size.width;
    CGFloat height = size.height;
    NSLog(@"print %f * %f",width,height);

    // 分辨率
    CGFloat scale_screen = [UIScreen mainScreen].scale;
//     进行图片像素压缩
    resultImage = [self compressImage:resultImage newWidth:SCREEN_WIDTH * scale_screen];
//    CGFloat targetLength = 200 * 1024;  // 目标大小为200KB
    // 进行图片质量压缩
//    if (imgData.length > targetLength) {z
//       resultImage = [resultImage compassImageToLength:targetLength];
//    }
    /**
    保存前往填写工作内容的图片
     **/
    
    NSDictionary *tIFFDictionary =  [imageMetadata objectForKey:(NSString *)kCGImagePropertyTIFFDictionary];
     NSString *dateTime = tIFFDictionary[@"DateTime"]; // 2016:01:05 11:45:36
    if ([Toolobject IsEmptyString:dateTime]) {
                dateTime = [Toolobject stringFromDate:[NSDate date] WithFormatter:@"yyyy:MM:dd HH:mm:ss"];
            }
        if (self.completion) {
            self.completion(resultImage, dateTime);
        }
        
         [self.preController dismissViewControllerAnimated:YES completion:Nil];

//    NSString *dateTime = tIFFDictionary[@"DateTime"]; // 2016:01:05 11:45:36
    //
//    if ([Toolobject IsEmptyString:dateTime]) {
//        dateTime = [Toolobject stringFromDate:[NSDate date] WithFormatter:@"yyyy:MM:dd HH:mm:ss"];
//    }
    
}

/**
 *  等比缩放本图片大小
 *
 *  @param newImageWidth 缩放后图片宽度，像素为单位
 *
 *  @return self-->(image)
 */
- (UIImage *)compressImage:(UIImage *)image newWidth:(CGFloat)newImageWidth {
    
    if (!image) return nil;
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = newImageWidth;
    float height = image.size.height/(image.size.width/width);
    float widthScale = imageWidth /width;
    float heightScale = imageHeight /height;
    
    // 创建一个 bitmap 的 context
    // 并把它设置成为当前正在使用的 context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth /heightScale ,height)];
    }
    else {
        [image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
    }
    // 从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    return newImage;
}

@end
